from django.contrib import admin
from .models import InGarageReport, CompletionFeedback, Garage, OutGarageReport, OgrCompletionFeedback
from django.utils.html import format_html
from django import forms
import requests
import random
import string
from django.urls import path
from django.shortcuts import redirect, render
from django.contrib import messages

from django.conf import settings    

admin.site.site_header = "车库管理系统"
admin.site.site_title  = "车库管理系统"
admin.site.index_title = "欢迎使用车库管理系统"


# 发送短信的示例函数
def send_sms(phone_number, message):
    # 假设你有一个短信发送API，在此调用实际的发送逻辑
    # 你可以使用 requests.post 或者其他发送短信的 SDK

    # message = (
    # f"车辆信息：{pickup_car_info}; 提车码：{pickup_code}; "
    # f"提车位置：{pickup_location}; 总部电话：{pickup_service_phone}; 注意事项：{pickup_notes}"
    # )
    print(f"发送短信至 {phone_number}，内容：{message}")

    if True:
        appcode = settings.APPCODE
        api = settings.SMS_API
        #请求参数（Query）
        mobile = phone_number
        templateId =settings.TEMPLATEID
        smsSignId  = settings.SMSSIGNID
        param = message
        #请求头
        headers = {
            'Authorization': 'APPCODE ' + appcode,
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
        #请求体
        data = {
            'mobile': mobile,
            'templateId': templateId,
            'smsSignId': smsSignId,
            'param': param
        }
        #发送请求
        response = requests.post(api, headers=headers, data=data)
        #打印响应
        print(response.text)




################################################################################
#
# InGarageReport --- Admin
#
################################################################################
class CompletionFeedbackInline(admin.TabularInline):
# class CompletionFeedbackInline(admin.StackedInline):
    model = CompletionFeedback
    # fields = ['description', 'display_image'] 
    list_display = ['description', 'display_image']
    extra = 0
    readonly_fields = ['display_image']  # 使用 display_image 来显示图片
    can_delete = True  # 可以选择是否允许删除完成反馈

    def get_formset(self, request, obj=None, **kwargs):
        formset = super().get_formset(request, obj, **kwargs)
        if not request.user.is_superuser:
            formset.form.base_fields.pop('images', None)
        return formset

    # 自定义显示图片的方式
    def display_image(self, obj):
        if obj.images:
            return format_html('<a href={} target="_blank"><img src="{}" style="width: 100px; height: auto;" /></a>', obj.images.url,obj.images.url)
        return "无图片"

    display_image.short_description = "照片"

    def has_add_permission(self, request, obj=None):
        # 乙方管理员允许添加反馈信息
        if request.user.is_superuser:
            return True
        return False


# 自定义表单
class InGarageReportForm(forms.ModelForm):
    class Meta:
        model = InGarageReport
        fields = '__all__'  # 确保包含所有字段

    def __init__(self, *args, **kwargs):
        # 传递 current_user
        self.current_user = kwargs.pop('current_user', None)
        super().__init__(*args, **kwargs)

        # 如果是甲方用户，隐藏 'status' 字段
        if self.current_user and not self.current_user.is_superuser:
            self.fields.pop('status')  # 动态删除 'status' 字段




# InGarageReport 的 Admin 配置
@admin.register(InGarageReport)
class InGarageReportAdmin(admin.ModelAdmin):
    form = InGarageReportForm

    list_display = ('license_plate', 'garage_name', 'created_at', 'completion_date',  'status')

    list_filter = ('status', 'garage_name')
    search_fields = ('license_plate', 'vin', 'user__username')


    fieldsets =  (

        ('用户入库报备信息', {
            'fields': ( 'garage_name', 'license_plate', 'vin', 'vehicle_model', 'vehicle_type',
                'delivery_person', 'delivery_phone', 'delivery_date', 'storage_method',
                'payment_link','return_address', 'remarks', ),
            
        }),

        ('管理员填写', {
            'fields': (         'task_date', 'completion_date', 'cost', 'charge_standard', 'has_key',
                'door_status', 'has_license', 'has_items', 'has_damage', 'has_seal', 'status', 'admin_remarks',),
        }),
      
    )



    # 嵌入 CompletionFeedback 信息
    inlines = [CompletionFeedbackInline]

    class Media:
        css = {
            'all': ('admin_custom.css',)  # 引入自定义的 CSS 文件
        }

    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path(
                '<path:object_id>/cancel/',
                self.admin_site.admin_view(self.cancel_report),
                name='ingaragereport_cancel',
            ),
        ]
        return custom_urls + urls

    def cancel_report(self, request, object_id):
        """
        处理状态修改为 "已取消"
        """
        report = self.get_object(request, object_id)
        if report.status == 1:  # 1 为 "待入库" 状态
            report.status = 2  # 2 为 "已取消" 状态
            report.save()
            self.message_user(request, "报备记录已取消", level=messages.SUCCESS)
        else:
            self.message_user(request, "该记录无法取消", level=messages.ERROR)
        return redirect('admin:vr_ingaragereport_change', object_id)

    def change_view(self, request, object_id, form_url='', extra_context=None):
        """
        修改页面时，甲方用户在状态为 "待入库" 时显示取消按钮，乙方管理员不显示
        """
        extra_context = extra_context or {}
        report = self.get_object(request, object_id)
        # 仅在甲方用户且记录为 "待入库" 时显示按钮
        if not request.user.is_superuser and report.status == 1:
            extra_context['show_cancel_button'] = True
        return super().change_view(request, object_id, form_url, extra_context=extra_context)


        

    def get_readonly_fields(self, request, obj=None):
        """
        根据用户角色动态设置只读字段
        - 乙方管理员可以编辑记录，甲方字段为只读
        - 甲方用户只能查看且不能编辑记录
        """
        if request.user.is_superuser:
            # 乙方管理员登录，甲方填写的字段为只读
            return [
                'user', 'created_at', 'garage_name', 'license_plate', 'vin', 'vehicle_model', 'vehicle_type',
                'delivery_person', 'delivery_phone', 'delivery_date', 'storage_method',
                'payment_link', 'remarks', 'return_address'
            ]
        else:
            # 甲方用户登录，所有字段为只读，但允许看到 CompletionFeedback 信息
            return [
                'task_date', 'completion_date', 'cost', 'charge_standard', 'has_key',
                'door_status', 'has_license', 'has_items', 'has_damage', 'has_seal', 'status', 'admin_remarks', 'payment_link'
            ]

        
        # 如果是甲方用户登录，所有字段为只读，但允许看到 CompletionFeedback 信息
        if obj and obj.user == request.user:
            return [
                'task_date', 'completion_date', 'cost', 'charge_standard', 'has_key',
                'door_status', 'has_license', 'has_items', 'has_damage', 'has_seal', 'status', 'admin_remarks', 
                'user', 'created_at', 'garage_name', 'license_plate', 'vin', 'vehicle_model', 'vehicle_type',
                'has_key', 'delivery_person', 'delivery_phone', 'delivery_date', 'storage_method',
                'payment_link', 'remarks', 'return_address'
            ]
        

        return super().get_readonly_fields(request, obj)


    def get_form(self, request, obj=None, **kwargs):
        """
        通过重写 get_form 方法，将当前用户传递给表单，以便根据用户角色决定显示的 "记录状态" 选项。
        """
        form = super().get_form(request, obj, **kwargs)
        # 传递当前用户到自定义表单
        form.current_user = request.user
        return form
    
    

    def get_queryset(self, request):
        """
        甲方用户只能查看自己的记录，乙方管理员可以查看所有记录。
        """
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(user=request.user)


    def get_fields(self, request, obj=None):
        """
        根据用户角色控制显示哪些字段。
        """
        if request.user.is_superuser:
            # 乙方管理员可以编辑所有字段，但甲方字段为只读
            return super().get_fields(request, obj)
        else:
            # 甲方用户只能看到和编辑自己填写的字段
            return [
                'garage_name', 'license_plate', 'vin', 'vehicle_model', 'vehicle_type', 
                'delivery_person', 'delivery_phone', 'delivery_date', 'storage_method', 
                'remarks', 'return_address', 'status'

                # the following is admin fill info, readonly
                # 'task_date', 'completion_date', 'cost', 'admin_remarks', 'charge_standard', 'has_key',
                # 'door_status', 'has_license', 'has_items', 'has_damage', 'has_seal', 'status',
            ]

    
    # 使支付链接字段只读，并根据费用大于0显示支付按钮
    readonly_fields = ['payment_button']

    def payment_button(self, obj):
        if obj.cost > 0 and obj.payment_link:
            return format_html('<a class="button" href=" " target="_blank">支付</a >', obj.payment_link)
        return "无支付链接"

    payment_button.short_description = "支付链接"



    # def save_model(self, request, obj, form, change):
    #     """
    #     自动设置记录状态和用户字段。
    #     """
    #     if not obj.pk:
    #         obj.user = request.user
    #         obj.status = 1  # 默认设置为 "待入库"
    #     super().save_model(request, obj, form, change)


    def save_model(self, request, obj, form, change):
        """
        在保存时自动将甲方用户的 'status' 设置为 '待入库'。
        """
        if not obj.pk:  # 如果是新增记录
            obj.user = request.user  # 设置甲方用户为当前用户
            if not request.user.is_superuser:  # 甲方用户提交时默认 'status' 为 '待入库'
                obj.status = 1  # '待入库' 状态
        super().save_model(request, obj, form, change)



    # 禁止乙方管理员添加新记录
    def has_add_permission(self, request):
        # 如果是超级用户（乙方管理员），禁止添加新记录
        if request.user.is_superuser:
            return False
        # 其他用户（甲方用户）可以根据权限添加
        return True



admin.site.register(Garage)


################################################################################
#
# OutGarageReportAdmin --- Admin
#
################################################################################

class OgrCompletionFeedbackInline(admin.TabularInline):
    model = OgrCompletionFeedback
    # fields = ['description', 'display_image'] 
    extra = 0
    readonly_fields = ['display_image']  # 使用 display_image 来显示图片
    can_delete = True  # 可以选择是否允许删除完成反馈

    def get_formset(self, request, obj=None, **kwargs):
        formset = super().get_formset(request, obj, **kwargs)
        if not request.user.is_superuser:
            formset.form.base_fields.pop('images', None)
        return formset
    
    # 自定义显示图片的方式
    def display_image(self, obj):
        if obj.images:
            return format_html('<a href={} target="_blank"><img src="{}" style="width: 100px; height: auto;" /></a>', obj.images.url,obj.images.url)
        return "无图片"

    display_image.short_description = "照片"

    def has_add_permission(self, request, obj=None):
        # 乙方管理员允许添加反馈信息
        if request.user.is_superuser:
            return True
        return False


@admin.register(OutGarageReport)
class OutGarageReportAdmin(admin.ModelAdmin):
    list_display = ('license_plate', 'client_name', 'status', 'created_at', 'completion_date', 'payment_status', 'status')
    list_filter = ('status', 'payment_status', 'client_name')
    search_fields = ('license_plate', 'client_name')

    exclude = ['payment_link']  # 隐藏 payment_link 字段

    inlines = [OgrCompletionFeedbackInline]  # 将反馈内联展示


    # readonly_fields = ['payment_link_display']  

    def payment_link_display(self, obj):
        """
        显示可点击的支付链接
        """
        if obj.payment_link:
            return format_html('<a href="{}" target="_blank">{}</a>', obj.payment_link, obj.payment_link)
        return "-"

    payment_link_display.short_description = "支付链接"



    class Media:
        css = {
            'all': ('admin_custom.css',)  # 引入自定义的 CSS 文件
        }

    def get_readonly_fields(self, request, obj=None):
        if request.user.is_superuser:
            # 乙方管理员可以编辑字段，甲方字段只读
            return ['user', 'created_at', 'client_name', 'license_plate', 'item_status', 'parking_fee_payer', 'picker_name', 'picker_id_number', 'picker_phone', 'pickup_date', 'payment_link_display', 'exit_method', 'remarks']
        else:
            # 甲方用户可以编辑1-13字段，乙方字段只读
            return ['task_date', 'completion_date', 'cost', 'admin_remarks', 'status', 'parking_duration', 'payment_link_display', 'payment_status']


    def get_fields(self, request, obj=None):
        if request.user.is_superuser:
            fields = super().get_fields(request, obj)
            # 乙方管理员不需要编辑注意事项字段，该字段有默认值
            fields.remove('pickup_notes')  
            return fields
        else:
            # 甲方用户只显示1-13字段
            return ['client_name', 'license_plate', 'item_status', 'parking_fee_payer', 'picker_name', 'picker_id_number', 'picker_phone', 'pickup_date', 'payment_link_display', 'exit_method', 'remarks']

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(user=request.user)

    # def save_model(self, request, obj, form, change):
    #     # 当甲方用户提交时，自动设置状态为 '已提交'
    #     if not obj.pk:
    #         obj.user = request.user
    #         obj.status = 1  # 已提交状态
    #     super().save_model(request, obj, form, change)


    def save_model(self, request, obj, form, change):
        # 当甲方用户提交时，自动设置状态为 '已提交'
        if not obj.pk:
            obj.user = request.user
            obj.status = 1  # 已提交状态
        else:
            # 检查状态是否从未完成变为已完成（假设状态为 2 表示已完成）
            if obj.status == 2 and 'status' in form.changed_data:
                # 获取需要发送短信的相关信息
                pickup_car_info = obj.license_plate  # 车辆信息
                # pickup_code = obj.pickup_code  # 提车码

                if obj.pickup_code:
                    pickup_code = obj.pickup_code
                else:
                    # create a new pickup code, 6位随机大写字母加数字字符串
                    pickup_code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))  
                    obj.pickup_code = pickup_code

                pickup_location = obj.pickup_location  # 记录提车位置
                pickup_service_phone = obj.pickup_service_phone  # 总部电话号码
                pickup_notes = obj.pickup_notes  # 注意事项
                
                # 构造短信内容
                message = (
                    f"车辆信息：{pickup_car_info}; 提车码：{pickup_code}; "
                    f"提车位置：{pickup_location}; 总部电话：{pickup_service_phone}; 注意事项：{pickup_notes}"
                )
                
                # 调用发送短信接口
                send_sms(obj.picker_phone, message)
        
        super().save_model(request, obj, form, change)


    # 禁止乙方管理员添加新记录
    def has_add_permission(self, request):
        # 如果是超级用户（乙方管理员），禁止添加新记录
        if request.user.is_superuser:
            return False
        # 其他用户（甲方用户）可以根据权限添加
        return True
    

################################################################################
#
# VehicleMaintenance --- Admin
#
################################################################################

from .models import VehicleMaintenance, VmCompletionFeedback

# 定义 VmCompletionFeedback 的内联表单
class VmCompletionFeedbackInline(admin.TabularInline):
    model = VmCompletionFeedback
    # fields = ['description', 'display_image'] 
    extra = 0
    readonly_fields = ['display_image']  # 使用 display_image 来显示图片
    can_delete = True  # 可以选择是否允许删除完成反馈

    def get_formset(self, request, obj=None, **kwargs):
        formset = super().get_formset(request, obj, **kwargs)
        if not request.user.is_superuser:
            formset.form.base_fields.pop('images', None)
        return formset
    
    # 自定义显示图片的方式
    def display_image(self, obj):
        if obj.images:
            return format_html('<a href={} target="_blank"><img src="{}" style="width: 100px; height: auto;" /></a>', obj.images.url,obj.images.url)
        return "无图片"

    display_image.short_description = "照片"

    def has_add_permission(self, request, obj=None):
        # 乙方管理员允许添加反馈信息
        if request.user.is_superuser:
            return True
        return False



# 自定义 VehicleMaintenance 的 Admin
@admin.register(VehicleMaintenance)
class VehicleMaintenanceAdmin(admin.ModelAdmin):
    list_display = ('license_plate', 'client_name', 'status', 'created_at', 'completion_date', 'payment_status')
    list_filter = ('status', 'payment_status', 'client_name')
    search_fields = ('license_plate', 'client_name')

    inlines = [VmCompletionFeedbackInline]  # 将反馈信息内联显示

    class Media:
        css = {
            'all': ('admin_custom.css',)  # 引入自定义的 CSS 文件
        }

    def get_readonly_fields(self, request, obj=None):
        if request.user.is_superuser:
            # 乙方管理员可以编辑字段，甲方字段只读
            return ['user', 'created_at', 'client_name', 'license_plate', 'maintenance_content', 'payment_method', 'payment_link', 'remarks']
        else:
            # 甲方用户可以编辑字段9-14的乙方字段只读
            return ['maintenance_date', 'completion_date', 'cost', 'admin_remarks', 'status', 'payment_status']

    def get_fields(self, request, obj=None):
        if request.user.is_superuser:
            # 乙方管理员可以看到所有字段
            return super().get_fields(request, obj)
        else:
            # 甲方用户只能看到1-8字段
            return ['client_name', 'license_plate', 'maintenance_content', 'payment_method', 'payment_link', 'remarks']

    def get_queryset(self, request):
        # 甲方用户只能看到自己的记录，乙方可以看到所有记录
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(user=request.user)

    def save_model(self, request, obj, form, change):
        # 当甲方用户提交时，状态默认为 '已提交'
        if not obj.pk:
            obj.user = request.user
            if not request.user.is_superuser:
                obj.status = 1  # '已提交'
        super().save_model(request, obj, form, change)

    # 禁止乙方管理员添加新记录
    def has_add_permission(self, request):
        # 如果是超级用户（乙方管理员），禁止添加新记录
        if request.user.is_superuser:
            return False
        # 其他用户（甲方用户）可以根据权限添加
        return True
    

################################################################################
#
# ItemSentback --- Admin
#
################################################################################

from .models import ItemSentback, IsbCompletionFeedback

# 定义 IsbCompletionFeedback 的内联表单
class IsbCompletionFeedbackInline(admin.TabularInline):
    model = IsbCompletionFeedback
    # fields = ['description', 'display_image'] 
    extra = 0
    readonly_fields = ['display_image']  # 使用 display_image 来显示图片
    can_delete = True  # 可以选择是否允许删除完成反馈

    def get_formset(self, request, obj=None, **kwargs):
        formset = super().get_formset(request, obj, **kwargs)
        if not request.user.is_superuser:
            formset.form.base_fields.pop('images', None)
        return formset
    
    # 自定义显示图片的方式
    def display_image(self, obj):
        if obj.images:
            return format_html('<a href={} target="_blank"><img src="{}" style="width: 100px; height: auto;" /></a>', obj.images.url,obj.images.url)
        return "无图片"

    display_image.short_description = "照片"

    def has_add_permission(self, request, obj=None):
        # 乙方管理员允许添加反馈信息
        if request.user.is_superuser:
            return True
        return False



# 自定义 ItemSentback 的 Admin
@admin.register(ItemSentback)
class ItemSentbackAdmin(admin.ModelAdmin):
    list_display = ('license_plate', 'client_name', 'status', 'created_at', 'completion_date', 'payment_status', 'status')
    list_filter = ('status', 'payment_status', 'client_name')
    search_fields = ('license_plate', 'client_name')

    inlines = [IsbCompletionFeedbackInline]  # 将反馈信息内联显示

    class Media:
        css = {
            'all': ('admin_custom.css',)  # 引入自定义的 CSS 文件
        }

    def get_readonly_fields(self, request, obj=None):
        if request.user.is_superuser:
            # 乙方管理员可以编辑字段，甲方字段只读
            return ['user', 'created_at', 'client_name', 'license_plate', 'payment_link', 'remarks', 'tracking_number']
        else:
            # 甲方用户可以编辑字段1-7，乙方字段只读
            return ['service_date', 'completion_date', 'cost', 'admin_remarks', 'status', 'payment_status']

    def get_fields(self, request, obj=None):
        if request.user.is_superuser:
            # 乙方管理员可以看到所有字段
            return super().get_fields(request, obj)
        else:
            # 甲方用户只能看到1-7字段
            return ['client_name', 'license_plate', 'payment_link', 'remarks', 'tracking_number']

    def get_queryset(self, request):
        # 甲方用户只能看到自己的记录，乙方可以看到所有记录
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(user=request.user)

    def save_model(self, request, obj, form, change):
        # 当甲方用户提交时，状态默认为 '已提交'
        if not obj.pk:
            obj.user = request.user
            if not request.user.is_superuser:
                obj.status = 1  # '已提交'
        super().save_model(request, obj, form, change)

    # 禁止乙方管理员添加新记录
    def has_add_permission(self, request):
        # 如果是超级用户（乙方管理员），禁止添加新记录
        if request.user.is_superuser:
            return False
        # 其他用户（甲方用户）可以根据权限添加
        return True


################################################################################
#
# KeyDuplication --- Admin
#
################################################################################

from .models import KeyDuplication, KdCompletionFeedback

# 定义 KdCompletionFeedback 的内联表单
class KdCompletionFeedbackInline(admin.TabularInline):
    model = KdCompletionFeedback
    # fields = ['description', 'display_image'] 
    extra = 0
    readonly_fields = ['display_image']  # 使用 display_image 来显示图片
    can_delete = True  # 可以选择是否允许删除完成反馈

    def get_formset(self, request, obj=None, **kwargs):
        formset = super().get_formset(request, obj, **kwargs)
        if not request.user.is_superuser:
            formset.form.base_fields.pop('images', None)
        return formset
    
    # 自定义显示图片的方式
    def display_image(self, obj):
        if obj.images:
            return format_html('<a href={} target="_blank"><img src="{}" style="width: 100px; height: auto;" /></a>', obj.images.url,obj.images.url)
        return "无图片"

    display_image.short_description = "照片"

    def has_add_permission(self, request, obj=None):
        # 乙方管理员允许添加反馈信息
        if request.user.is_superuser:
            return True
        return False



# 自定义 KeyDuplication 的 Admin
@admin.register(KeyDuplication)
class KeyDuplicationAdmin(admin.ModelAdmin):
    list_display = ('license_plate', 'client_name', 'status', 'created_at', 'completion_date', 'payment_status', 'status')
    list_filter = ('status', 'payment_status', 'client_name')
    search_fields = ('license_plate', 'client_name')

    inlines = [KdCompletionFeedbackInline]  # 将反馈信息内联显示

    class Media:
        css = {
            'all': ('admin_custom.css',)  # 引入自定义的 CSS 文件
        }

    def get_readonly_fields(self, request, obj=None):
        if request.user.is_superuser:
            # 乙方管理员可以编辑字段，甲方字段只读
            return ['user', 'created_at', 'client_name', 'license_plate', 'task_description', 'payment_method', 'payment_link', 'return_items', 'return_address', 'remarks']
        else:
            # 甲方用户可以编辑字段1-10，乙方字段只读
            return ['task_date', 'completion_date', 'cost', 'admin_remarks', 'status', 'payment_status']

    def get_fields(self, request, obj=None):
        if request.user.is_superuser:
            # 乙方管理员可以看到所有字段
            return super().get_fields(request, obj)
        else:
            # 甲方用户只能看到1-10字段
            return ['client_name', 'license_plate', 'task_description', 'payment_method', 'payment_link', 'return_items', 'return_address', 'remarks']

    def get_queryset(self, request):
        # 甲方用户只能看到自己的记录，乙方可以看到所有记录
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(user=request.user)

    def save_model(self, request, obj, form, change):
        # 当甲方用户提交时，状态默认为 '已提交'
        if not obj.pk:
            obj.user = request.user
            if not request.user.is_superuser:
                obj.status = 1  # '已提交'
        super().save_model(request, obj, form, change)

    # 禁止乙方管理员添加新记录
    def has_add_permission(self, request):
        # 如果是超级用户（乙方管理员），禁止添加新记录
        if request.user.is_superuser:
            return False
        # 其他用户（甲方用户）可以根据权限添加
        return True



################################################################################
#
# MailKey --- Admin
#
################################################################################

from .models import MailKey, MkCompletionFeedback

# 定义 MkCompletionFeedback 的内联表单
class MkCompletionFeedbackInline(admin.TabularInline):
    model = MkCompletionFeedback
    # fields = ['description', 'display_image'] 
    extra = 0
    readonly_fields = ['display_image']  # 使用 display_image 来显示图片
    can_delete = True  # 可以选择是否允许删除完成反馈

    def get_formset(self, request, obj=None, **kwargs):
        formset = super().get_formset(request, obj, **kwargs)
        if not request.user.is_superuser:
            formset.form.base_fields.pop('images', None)
        return formset
    
    # 自定义显示图片的方式
    def display_image(self, obj):
        if obj.images:
            return format_html('<a href={} target="_blank"><img src="{}" style="width: 100px; height: auto;" /></a>', obj.images.url,obj.images.url)
        return "无图片"

    display_image.short_description = "照片"

    def has_add_permission(self, request, obj=None):
        # 乙方管理员允许添加反馈信息
        if request.user.is_superuser:
            return True
        return False



# 自定义 MailKey 的 Admin
@admin.register(MailKey)
class MailKeyAdmin(admin.ModelAdmin):
    list_display = ('license_plate', 'client_name', 'status', 'created_at', 'completion_date', 'payment_status', 'status')
    list_filter = ('status', 'payment_status', 'client_name')
    search_fields = ('license_plate', 'client_name')

    inlines = [MkCompletionFeedbackInline]  # 将反馈信息内联显示

    class Media:
        css = {
            'all': ('admin_custom.css',)  # 引入自定义的 CSS 文件
        }

    def get_readonly_fields(self, request, obj=None):
        if request.user.is_superuser:
            # 乙方管理员可以编辑字段，甲方字段只读
            return ['user', 'created_at', 'client_name', 'license_plate', 'task_description', 'tracking_number', 'payment_link', 'remarks', 'return_items', 'return_address']
        else:
            # 甲方用户可以编辑字段1-9，乙方字段只读
            return ['task_date', 'completion_date', 'cost', 'admin_remarks', 'status', 'payment_status']

    def get_fields(self, request, obj=None):
        if request.user.is_superuser:
            # 乙方管理员可以看到所有字段
            return super().get_fields(request, obj)
        else:
            # 甲方用户只能看到1-9字段
            return ['client_name', 'license_plate', 'task_description', 'tracking_number', 'payment_link', 'remarks', 'return_items', 'return_address']

    def get_queryset(self, request):
        # 甲方用户只能看到自己的记录，乙方可以看到所有记录
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(user=request.user)

    def save_model(self, request, obj, form, change):
        # 当甲方用户提交时，状态默认为 '已提交'
        if not obj.pk:
            obj.user = request.user
            if not request.user.is_superuser:
                obj.status = 1  # '已提交'
        super().save_model(request, obj, form, change)

    # 禁止乙方管理员添加新记录
    def has_add_permission(self, request):
        # 如果是超级用户（乙方管理员），禁止添加新记录
        if request.user.is_superuser:
            return False
        # 其他用户（甲方用户）可以根据权限添加
        return True
    
